{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "'''\n",
    "优化原则\n",
    "1.定点计算快于浮点运算\n",
    "2.加减运算快于乘除运算\n",
    "3,移位运算快于乘除运算\n",
    "'''\n",
    "img = cv2.imread('image0.jpg',1)\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "# BGR 算法：gray = w1*b+w2*g+w3*r w1,w2,w3代表权重\n",
    "dstImg = np.zeros((height,width,3),np.uint8)\n",
    "for i in range(0,height):\n",
    "    for j in range(0,width):\n",
    "        (b,g,r) = img[i,j]\n",
    "        # 原类型为uint8相加后可能会溢出，转换为int类型防止出现越界\n",
    "        b = int(b)\n",
    "        g = int(g)\n",
    "        r = int(r)\n",
    "        # 浮点转定点，整体乘4再除4，存在误差。乘的数越大，误差越小。可以尝试乘1000再除1000\n",
    "        # gray = (r*1+g*2+b*1)/4\n",
    "        # 继续优化 定点转移位\n",
    "        gray = (r+(g<<1)+b)>>2\n",
    "        dstImg[i,j] = np.uint8(gray)\n",
    "cv2.imshow('dstImg',dstImg)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
